//
//  LGTRWZAppendTaskVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/30.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

class LGTRWZAppendTaskVC: LGTBaseVC {
    
    var coutTextView:LGTInputTextView?
    var topTextView:LGTInputTextView?
    var countMoneyLabel:UILabel?
    var descLabel:UILabel?
    var offlineLabel:UILabel?
    var fromNav:UINavigationController?
    var paramModel:PostParamModel?
    var submitInfo:Dictionary<String, Any>?
    var detailLabel:UILabel?
    var textChangeBlock:ClickReturnStrBlock?  //键盘文字变化回掉处理
    var textChangeBlock2:ClickReturnStrBlock?  //键盘文字变化回掉处理
    var taskCount:Int = 0 //任务数量
    var topCount:Int = 0 //置顶天数
    var timeStr:String = "" //下线时间
    var totalPrice:CGFloat = 0 //总花的费用
    var selectCell:LGTRWZPostSelectCell?
    var offlieModel:Dictionary<String, Any> = ["title":"下线日期", "subText":""]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(paySuccessAction), name: Pay_Success_Note, object: nil)
    }
    
    @objc func paySuccessAction(){
        
        self.dismiss(animated: false, completion: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: Pay_Success_Note, object: nil)
    }
    
    
    override func setUI() {
        super.setUI()
        self.view.backgroundColor = BlackAlpha46
        let backView:UIView = UIView.init()
        backView.backgroundColor = UIColor.white
        self.view.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(IPHONETabbar_DIS() + SizeFit(387))
        }
        
        //下一步
        let nextButton:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "下一步", font: Font_Normal_18, color: UIColor.white, selectedColor: UIColor.white,  corner: SizeFitFloat(22), backColor: YellowColor)
        backView.addSubview(nextButton)
        nextButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.bottom.equalTo(-(SizeFit(17) + IPHONETabbar_DIS()))
            make.height.equalTo(SizeFitFloat(44))
            make.width.equalTo(SizeFit(330))
        }
        nextButton.addTarget(self, action: #selector(nextStep), for: UIControl.Event.touchUpInside)
        
        let titleLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "追加任务")
        titleLabel.font = Font_Bold_18
        backView.addSubview(titleLabel)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(backClick))
        backView.addGestureRecognizer(tap)
        let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(backClick))
        self.view.addGestureRecognizer(tap2)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(14))
            make.top.equalTo(SizeFit(24))
            make.height.equalTo(SizeFit(19))
        }
        
        let addTaskCountLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "追加任务数量")
        backView.addSubview(addTaskCountLabel)
        addTaskCountLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(32))
            make.top.equalTo(SizeFit(76))
            make.height.equalTo(SizeFit(19))
        }
        
        self.coutTextView = LGTViewCreateUtil.share.createInputTextView(placehoder: "", fontSize:SizeFitFloat(18), limitCout: 11)
        backView.addSubview(self.coutTextView!)
        self.coutTextView!.snp.makeConstraints({ (make) in
            make.height.equalTo(SizeFitFloat(18))
            make.left.equalTo(addTaskCountLabel.snp_rightMargin).offset(SizeFitFloat(9))
            make.width.equalTo(SizeFitFloat(84))
            make.top.equalTo(SizeFitFloat(76))
        })
        
        let yellowImagView1:UIImageView = LGTViewCreateUtil.share.createLineView()
        yellowImagView1.backgroundColor = YellowColor
        backView.addSubview(yellowImagView1)
        yellowImagView1.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.left.equalTo(addTaskCountLabel.snp_rightMargin).offset(SizeFitFloat(9))
            make.width.equalTo(SizeFitFloat(84))
            make.top.equalTo(SizeFitFloat(95))
        }
        
        let coutLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "个")
        backView.addSubview(coutLabel)
        coutLabel.snp.makeConstraints { (make) in
            make.left.equalTo(yellowImagView1.snp_rightMargin).offset(SizeFitFloat(6))
            make.top.equalTo(SizeFit(76))
            make.height.equalTo(SizeFit(19))
        }
        
        let needLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: "（必填）")
        backView.addSubview(needLabel)
        needLabel.snp.makeConstraints { (make) in
            make.left.equalTo(coutLabel.snp_rightMargin).offset(SizeFitFloat(10))
            make.top.equalTo(SizeFit(80))
            make.height.equalTo(SizeFit(15))
        }
        
//        //任务费+服务费5%+保证金20%（保证金在任务下架后退还）
        let commission_rate:CGFloat = self.paramModel?.commission_rate ?? 0
        let deposit_rate:CGFloat = self.paramModel?.deposit_rate ?? 0
        let descStr:String = "任务费+服务费\(commission_rate)%+保证金\(deposit_rate)%（保证金在任务下架后退还）"
        let descLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: GrayColor, fontSize: SizeFitFloat(12), text: descStr)
        backView.addSubview(descLabel)
        descLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(33))
            make.height.equalTo(SizeFit(12))
            make.top.equalTo(SizeFit(109))
        }
        
        //置顶
        let topLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "置顶天数")
        backView.addSubview(topLabel)
        topLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(32))
            make.top.equalTo(SizeFit(143))
            make.height.equalTo(SizeFit(19))
        }

        self.topTextView = LGTViewCreateUtil.share.createInputTextView(placehoder: "", fontSize:SizeFitFloat(18), limitCout: 11)
        backView.addSubview(self.topTextView!)
        self.topTextView!.snp.makeConstraints({ (make) in
            make.height.equalTo(SizeFit(18))
            make.left.equalTo(topLabel.snp_rightMargin).offset(SizeFitFloat(9))
            make.width.equalTo(SizeFitFloat(84))
            make.top.equalTo(SizeFitFloat(143))
        })

        let yellowImagView2:UIImageView = LGTViewCreateUtil.share.createLineView()
        yellowImagView2.backgroundColor = YellowColor
        backView.addSubview(yellowImagView2)
        yellowImagView2.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.left.equalTo(topLabel.snp_rightMargin).offset(SizeFitFloat(9))
            make.width.equalTo(SizeFitFloat(84))
            make.top.equalTo(SizeFitFloat(162))
        }
        

        let dayLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "天")
        backView.addSubview(dayLabel)
        dayLabel.snp.makeConstraints { (make) in
            make.left.equalTo(yellowImagView2.snp_rightMargin).offset(SizeFitFloat(6))
            make.top.equalTo(SizeFit(143))
            make.height.equalTo(SizeFit(19))
        }

        let optionLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: "（选填）")
        backView.addSubview(optionLabel)
        optionLabel.snp.makeConstraints { (make) in
            make.left.equalTo(dayLabel.snp_rightMargin).offset(SizeFitFloat(10))
            make.top.equalTo(SizeFit(147))
            make.height.equalTo(SizeFit(15))
        }

        let countMoneyLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "合计：")
        backView.addSubview(countMoneyLabel)
        countMoneyLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(32))
            make.top.equalTo(SizeFit(182))
            make.height.equalTo(SizeFit(19))
        }

        self.countMoneyLabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: ColorUtil(color: 0xF43319), fontSize: SizeFitFloat(18), text: "0元")
        backView.addSubview(self.countMoneyLabel!)
        self.countMoneyLabel!.snp.makeConstraints { (make) in
            make.left.equalTo(countMoneyLabel.snp_rightMargin).offset(SizeFitFloat(10))
            make.height.equalTo(19)
            make.centerY.equalTo(countMoneyLabel)
        }
        
//        let offlineLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(18), text: "下线日期")
//        backView.addSubview(offlineLabel)
//        offlineLabel.snp.makeConstraints { (make) in
//            make.left.equalTo(SizeFit(32))
//            make.top.equalTo(SizeFit(244))
//            make.height.equalTo(SizeFit(19))
//        }
        
        
        //任务费
//        let  taskDetailLabel:UILabel =  LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: GrayColor, fontSize: SizeFitFloat(12), text: "")
        self.detailLabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: GrayColor, fontSize: SizeFitFloat(12), text: "")
        self.detailLabel?.numberOfLines = 4
        backView.addSubview(self.detailLabel!)
        self.detailLabel?.snp.makeConstraints({ (make) in
            make.top.equalTo(SizeFit(211))
            make.left.equalTo(SizeFit(33))
        })
        
        self.selectCell = LGTRWZPostSelectCell.init(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
        backView.addSubview(self.selectCell!)
        self.selectCell?.model = self.offlieModel
        self.selectCell?.titleLabel?.font = Font_Normal_18
        self.selectCell!.snp.makeConstraints { (make) in
            make.height.equalTo(SizeFit(41))
            make.left.equalTo(SizeFit(19))
            make.right.equalTo(SizeFit(-20))
            make.top.equalTo(self.detailLabel!.snp_bottomMargin).offset(SizeFit(20))
        }
        
        // 时间选择
        self.selectCell?.isUserInteractionEnabled = true
        let tap3:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(timeSelect))
        self.selectCell?.addGestureRecognizer(tap3)
        
        //值变化回掉
        weak  var weakSelf = self
        self.textChangeBlock = {
            (text:String) -> Void in
            weakSelf?.topTextView?.text = text
            weakSelf?.updateData(str: text, textView: weakSelf!.topTextView!)
        }
        
        self.textChangeBlock2 = {
            (text:String) -> Void in
            weakSelf?.coutTextView?.text = text
            weakSelf?.updateData(str: text, textView: weakSelf!.coutTextView!)
        }
        
        self.topTextView?.textView.keyboardType = UIKeyboardType.numberPad
        self.coutTextView?.textView.keyboardType = UIKeyboardType.numberPad
        self.topTextView?.textView.textAlignment = NSTextAlignment.center
        self.coutTextView?.textView.textAlignment = NSTextAlignment.center
        self.topTextView?.returnReturnStrBlock = self.textChangeBlock
        self.coutTextView?.returnReturnStrBlock = self.textChangeBlock2
    }
    
    @objc func nextStep(){
        let submiteInfo:Dictionary<String, Any> = ["num": self.taskCount,
                                                   "id": self.submitInfo?["id"] as? Int ?? 0,
                                                   "top_time_limit": self.topCount,
                                                   "end_time": self.offlieModel["subText"] as? String ?? "",
                                                   "payMoney": Double(self.totalPrice)]
        
        //发布
        LGTViewUtil.share.publicGotoPayVC(submitDataInfo: submiteInfo, stepArray: [], nav: self.fromNav!, payType:PayType.ApendPayType, fromVC: self)
    }
    
    func updateData(str:String, textView:LGTInputTextView){
        textView.text = str
        
        let price:CGFloat = CGFloat(Double(self.submitInfo?["workPrice"] as? String ?? "") ?? 0)
        self.topCount = Int(self.topTextView?.textView.text ?? "") ?? 0
        self.taskCount = Int(self.coutTextView?.textView.text ?? "") ?? 0
        let topprice:CGFloat = CGFloat(self.paramModel?.top_price ?? 0) / 100.0
        //置顶费用
        let topMony:CGFloat = topprice * CGFloat(self.topCount)
        //保证金
        let taskPrice:CGFloat = price * CGFloat(self.taskCount)
        //服务费
        let severPrice:CGFloat =  taskPrice * (self.paramModel?.commission_rate ?? 0.0) / 100
        //保证金
        let porsePrice:CGFloat = taskPrice * (self.paramModel?.deposit_rate ?? 0.0) / 100
        
        
        //总共花的多少钱
        self.totalPrice = taskPrice + severPrice + porsePrice + topMony
        self.countMoneyLabel?.text = "\(self.totalPrice)"
        self.detailLabel?.text = "任务费\(taskPrice)元+服务费\(severPrice)元+保证金\(porsePrice)元+置顶费用\(topMony)元"

        self.countMoneyLabel?.text = "\(self.totalPrice)"
    }
    
    
    @objc func timeSelect(){
        
        let vc:LGTRWZTimeSelectVC = LGTRWZTimeSelectVC()
        vc.currentDateStr = self.offlieModel["subText"] as? String ?? ""
        vc.path = IndexPath.init()
        weak var weakSelf = self
        vc.clickBlock =  { (_ data:PostNameModel,_ path:IndexPath) in
            weakSelf?.offlieModel["subText"] = data.name ?? ""
            weakSelf?.selectCell?.model = weakSelf?.offlieModel ?? [:]
        }
        
        vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: false, completion: nil)
    }
    
//    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.dismiss(animated: false, completion: nil)
//    }
//
    @objc func backClick(tap:UITapGestureRecognizer){
        if tap.view == self.view{
            self.dismiss(animated: false, completion: nil)
        }
    }
}

